import { ItemCompleteUseAfterEvent, world } from "@minecraft/server";
import { EffectData } from "../../common";

/**
 * Define a food item.
 */
export class FoodItem {
  constructor(
    /**
     * Identifier of the type of items for the stack. If a namespace is not specified, 'minecraft:' is assumed.
     */
    readonly typeId: string,
    /**
     * Adds a status effect when eat the food.
     */
    public statusEffects?: EffectData[],
    /**
     * This event fires when eat the food.
     */
    public eatEvent?: (arg: ItemCompleteUseAfterEvent) => void,
  ) {
    this.register();
  }
  /**
   * Registry the food.
   */
  protected register() {
    world.afterEvents.itemCompleteUse.subscribe((event) => {
      const [PLAYER, ITEM] = [event.source, event.itemStack];
      if (ITEM.typeId === this.typeId) {
        this.statusEffects?.forEach((data: EffectData) => {
          PLAYER.addEffect(data.effectType, data.duration, {
            amplifier: data.amplifier,
            showParticles: data.showParticles,
          });
        });
        if (this.eatEvent) {
          this.eatEvent(event);
        }
      }
    });
  }
}
